import 'dart:io';

import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' as GetX;
import 'package:image_picker/image_picker.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/widgets/image.dart';
import 'package:nft_shop/widgets/load_image.dart';

class SelectedImageUtils extends StatefulWidget {
  Function(String url)? determineBack;
  bool isFile;
  SelectedImageUtils({Key? key,this.determineBack,this.isFile = false});

  @override
  _SelectedImageUtilsState createState() => _SelectedImageUtilsState();
}

class _SelectedImageUtilsState extends State<SelectedImageUtils> {
  //实例化选择图片
  final ImagePicker picker = new ImagePicker();
  //用户本地图片
  File? _userImage;//存放获取到的本地路径

  //异步吊起相机拍摄新照片方法
  Future _getCameraImage() async {
    final cameraImages = await picker.getImage(source: ImageSource.camera,imageQuality: 30);
    if (mounted) {
      //拍摄照片不为空
      if (cameraImages != null) {
        _userImage = File(cameraImages.path);
        _upLoadImage(_userImage!);
        print('你选择的路径是：${_userImage.toString()}');
        //图片为空
      } else {
        print('没有照片可以选择');
      }
    }
  }

  Future _getImage() async {
    //选择相册
    final pickerImages = await picker.getImage(source: ImageSource.gallery,imageQuality: 30);
    if(mounted){
      // .contains('.svg');
      if(pickerImages != null){
        _userImage = File(pickerImages.path);
        print("路径地址111----${_userImage}");
        _upLoadImage(_userImage!);
        print('你选择的本地路径是：${_userImage.toString()}');
      }else{
        print('没有照片可以选择');
      }
    }else{
      print('选择照片失败---');
    }
  }

  Future _getGLBFile() async {
    print("手机有没有--");
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      if(!result.files.single.path!.contains('.glb')){
        EasyLoading.showToast("请选择glb格式文件");
        return;
      }
      _userImage = File(result.files.single.path!);
      _upLoadImage(_userImage!);
    } else {
      print("手机没有glb文件");
      // User canceled the picker
    }
  }


  //图片提交
  _upLoadImage(File image) async {
    String path = image.path;
    String name = path.substring(path.lastIndexOf("/") +1, path.length);

    FormData formdata = FormData.fromMap({
      "file": await MultipartFile.fromFileSync(path,filename:name,),
    });
    EasyLoading.show(status: "正在加载...");
    try{
      var url = await ServiceRepository.fileUpload(formdata);
      EasyLoading.dismiss();
      if(url.length != 0){
        widget.determineBack!(url);
        EasyLoading.showToast("上传成功");
      }
    }catch (e, s) {
      EasyLoading.showToast("上传失败");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.transparent,
      height: 190,
      width: 120,
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          Visibility(
            visible: !widget.isFile,
            child: _buildItem(
                title: "拍摄",
                border: BorderRadius.only(
                    topLeft: Radius.circular(4), topRight: Radius.circular(4)),
                onTap: ()async{
                  await _getCameraImage();
                  GetX.Get.back();
                }
            ),
          ),
          Visibility(
            visible: !widget.isFile,
            child: Container(
              color: Color(0xFFF5F5F5),
              height: 1,
              width: double.infinity,
            ),
          ),
          _buildItem(
              title: "从相册选择",
              border: BorderRadius.only(
                  bottomLeft: Radius.circular(4),
                  bottomRight: Radius.circular(4)),
              onTap: () async{
                if(widget.isFile){
                  await _getGLBFile();
                }else{
                  await _getImage();
                }
                GetX.Get.back();
              }
          ),
          SizedBox(
            height: 10,
          ),
          _buildItem(title: "取消", border: BorderRadius.circular(4),onTap: (){
            GetX.Get.back();
          }),
        ],
      ),
    );
  }

  //item
  Widget _buildItem(
      {required String title,
        BorderRadiusGeometry? border,
        GestureTapCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: border,
        ),
        height: 50,
        child: Center(
            child: Text(
              title,
              style: TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 16,
                  color: Color(0xFF2F73FD)),
            )),
      ),
    );
  }
}
